<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //扁形数组转成树形数组的函数：
        // 得到指pid下所有子对象组成的新数组
        function transListToTreeData(list, rootValue) {
            const array = []
            list.forEach(item => {
                if(item.pid === rootValue){
                    item.children = transListToTreeData(list, item.id)
                    array.push(item)
                }
            });
            return array
        }
        // 测试代码：
        var arr = [
            { id: 1, name: '总裁办', pid: 0 },
            { id: 11, name: '秘书处', pid: 1 },
            { id: 2, name: 'IT部', pid: 0 }
        ]

        var result = transListToTreeData(arr, 11)
        console.log(result); // []

        result = transListToTreeData(arr, 1)
        console.log(result); // [{ id: 11, name: '秘书处', pid: 1, children: [] }]

        result = transListToTreeData(arr, 0)
        console.log(result);
        // [
        //     { id: 1, name: '总裁办', pid: 0, children: [{ id: 11, name: '秘书处', pid: 1 }] },
        //     { id: 2, name: 'IT部', pid: 0 }
        // ]
    </script>
</body>

</html>